import type {
  IframeSDKConfig,
  QverseIframeSDKManagerInstance,
  TagData,
  SceneData,
  TagStyleData,
  TagTitleTextData
} from './iframeSDKManager.d'

import EventEmitter from 'eventemitter3'
import { IframeSDKEventMap } from './events'

const { MessageSDK } = window as any

export class IframeSDKManager extends EventEmitter<string, any> {
  private sdkInstance: QverseIframeSDKManagerInstance | null = null
  private isInitialized = false

  constructor() {
    super()
  }

  /**
   * 确保SDK已初始化
   */
  private ensureInitialized() {
    if (!this.isInitialized || !this.sdkInstance) {
      throw new Error('SDK not initialized. Please call init() first.')
    }
  }

  /**
   * 初始化SDK
   */
  async init(config: IframeSDKConfig): Promise<void> {
    if (this.isInitialized && this.sdkInstance) {
      console.warn('SDK already initialized')
      return
    }

    try {
      // 创建SDK实例
      const messageSDKInstance = await MessageSDK.connect({
        targetWindow: config.targetWindow,
        targetOrigin: config.targetOrigin,
        config: {
          hide_ui: ['all'],
          hide_loading: 'on'
        }
      })

      this.sdkInstance = messageSDKInstance
      this.isInitialized = true
      // 设置事件代理
      this._setupSDKEventProxy()

      console.log('IframeSDKManager initialized successfully')
    } catch (error) {
      console.error('Failed to initialize SDK:', error)

      throw error
    }
  }

  /**
   * 检查是否已初始化
   */
  isReady(): boolean {
    return this.isInitialized && this.sdkInstance !== null
  }

  /**
   * 标签相关操作
   */
  async getTags() {
    this.ensureInitialized()

    return await this.sdkInstance!.tag.getTags()
  }

  /**
   * 飞向指定标签
   * @param data
   * @returns
   */
  async flyToTag(data: TagData) {
    this.ensureInitialized()

    return await this.sdkInstance!.tag.flyTo(data)
  }

  /**
   * 设置标签样式
   * @param data
   */
  async setTagStyle(data: TagStyleData) {
    this.ensureInitialized()
    this.sdkInstance!.tag.setStyle({
      id: data.id,
      size: data.size
    })
  }

  /**
   * 设置标签标题
   * @param data
   */
  async setTagTitleText(data: TagTitleTextData) {
    this.ensureInitialized()
    this.sdkInstance!.tag.setTitleText({
      id: data.id,
      text: data.text
    })
  }

  /**
   * 获取场景列表
   */
  async getScenes() {
    this.ensureInitialized()

    return await this.sdkInstance!.scene.getScenes()
  }

  /**
   * 切换场景
   * @param data
   */
  switchScene(data: SceneData) {
    this.ensureInitialized()
    this.sdkInstance!.scene.switch(data)
  }

  /**
   * 返回场景
   * @returns
   */
  async backScene() {
    this.ensureInitialized()

    return await this.sdkInstance!.scene.back()
  }

  /**
   * 模式切换
   */
  switchMode(mode: string) {
    this.ensureInitialized()
    this.sdkInstance!.mode.switch(mode)
  }

  /**
   * 销毁
   */
  destroy() {
    this._removeAllEventProxy()
    this.sdkInstance = null
    this.isInitialized = false
  }

  /**
   * 设置事件代理
   */
  _setupSDKEventProxy() {
    Object.values(IframeSDKEventMap).forEach((eventName) => {
      this.sdkInstance!.on(eventName, (data: any) => {
        this.emit(eventName, data)
      })
    })
  }

  /**
   * 移除事件代理
   * @param eventName 移除事件代理
   */
  _removeAllEventProxy() {
    Object.values(IframeSDKEventMap).forEach((eventName) => {
      this.sdkInstance!.remove(eventName)
    })
  }
}
